package com.hyjy.music.util

import android.content.Context
import com.hyjy.music.ContextHolder
import java.io.*

/**
 * 把资产目录中音乐和歌词下载到手机
 *
 * @param assetsPath 从哪里下载
 * @param savePath 下载到手机哪个路径
 */
fun copyFileToPhone(assetsPath: String = "music", savePath: String, finish: () -> Unit) {
    var inputStream: InputStream? = null
    var fos: FileOutputStream? = null
    try {
        val list = ContextHolder.context.assets.list(assetsPath) // assets目录下的music
        if (list != null) {
            for (str in list) {
                if (!str.endsWith("mp3") && !str.endsWith("aac") && !str.endsWith("lrc")) {
                    continue
                }
                inputStream = ContextHolder.context.assets.open("$assetsPath/$str")
                val file = File(savePath, str)
                if (file.exists() && file.length() > 0) {
                    println(file.canonicalPath + ",无需拷贝")
                    continue
                }
                fos = FileOutputStream(file)
                val buffer = ByteArray(1024 * 5)
                var len: Int
                while (inputStream.read(buffer).also { len = it } != -1) {
                    fos.write(buffer, 0, len)
                }
                println(file.canonicalPath + ",拷贝成功")
            }
            finish.invoke()
        }
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        fos.closeStream()
        inputStream.closeStream()
    }
}

/**
 * 保存文件
 *
 * @param bytes 文件字节数组
 * @param destFileDir 文件的路径
 * @param destFileName 文件的名称
 * @return 保存好的文件
 */
fun saveFile(bytes: ByteArray, destFileDir: String, destFileName: String): File? {
    var fos: FileOutputStream? = null
    var bos: BufferedOutputStream? = null
    var file: File? = null
    try {
        val dir = File(destFileDir)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        file = File(destFileDir, destFileName)
        fos = FileOutputStream(file)
        bos = BufferedOutputStream(fos)
        bos.write(bytes)
        bos.flush()
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        bos.closeStream()
        fos.closeStream()
    }
    return file
}

/**
 * 保存一个对象到本地
 *
 * @param name 以什么文件名称保存
 * @return 是否保存成功
 */
infix fun Serializable.saveSerializableByName(name: String): Boolean {
    if (name.isEmpty()) {
        return false
    }
    var fos: FileOutputStream? = null
    var oos: ObjectOutputStream? = null
    return try {
        fos = ContextHolder.context.openFileOutput(name, Context.MODE_PRIVATE)
        oos = ObjectOutputStream(fos)
        oos.writeObject(this)
        true
    } catch (e: IOException) {
        e.printStackTrace()
        false
    } catch (e: ClassNotFoundException) {
        e.printStackTrace()
        false
    } finally {
        oos.closeStream()
        fos.closeStream()
    }
}

/**
 * 从本地获取一个对象
 *
 * @param name    文件名称
 * @return 要获取的对象
 */
fun <T> getSerializableByName(name: String?): T? {
    if (name.isNullOrEmpty()) {
        return null
    }
    var fis: FileInputStream? = null
    var ois: ObjectInputStream? = null
    return try {
        fis = ContextHolder.context.openFileInput(name)
        ois = ObjectInputStream(fis)
        val obj = ois.readObject()
        obj as? T
    } catch (e: IOException) {
        e.printStackTrace()
        null
    } catch (e: ClassNotFoundException) {
        e.printStackTrace()
        null
    } finally {
        fis.closeStream()
        ois.closeStream()
    }
}

fun Closeable?.closeStream() {
    try {
        this?.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

fun InputStream.toByteArray(): ByteArray? {
    return try {
        ByteArrayOutputStream().use {
            val buffer = ByteArray(1024)
            var num: Int
            while (read(buffer).also { len -> num = len } != -1) {
                it.write(buffer, 0, num)
            }
            it.flush()
            it.toByteArray()
        }
    } catch (e: IOException) {
        e.printStackTrace()
        null
    }
}